package com.peng.rpc.socket.server;

import com.peng.rpc.common.server.RequestHandler;
import com.peng.rpc.entity.RpcRequest;
import com.peng.rpc.entity.RpcResponse;
import com.peng.rpc.socket.util.ObjectReader;
import com.peng.rpc.socket.util.ObjectWriter;
import com.peng.rpc.provider.ServiceProvider;
import com.peng.rpc.serializer.CommonSerializer;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.Socket;

/**
 * @author Wonderson
 * @email wpp.ds@foxmail.com
 * @date 2022/2/28 20:26
 */
@Slf4j
public class SocketRequestHandlerThread implements Runnable{

    private final Socket socket;
    private final RequestHandler requestHandler;
    private final CommonSerializer serializer;

    public SocketRequestHandlerThread(Socket socket, RequestHandler requestHandler,
                                       CommonSerializer serializer) {
        this.socket = socket;
        this.requestHandler = requestHandler;
        this.serializer = serializer;
    }

    @Override
    public void run() {
        try (
                OutputStream os = socket.getOutputStream();
                InputStream is = socket.getInputStream();
        ) {
            RpcRequest rpcRequest = (RpcRequest) ObjectReader.readObject(is);
            Object result = requestHandler.handle(rpcRequest);
            RpcResponse<Object> success = RpcResponse.success(result, rpcRequest.getRequestId());
            log.info("接收到来自客户端：{}的请求：{}，经过处理后的返回值为：{}",
                    socket.getInetAddress() + ":" + socket.getPort(), rpcRequest, success);
            ObjectWriter.writeObject(os, success, serializer);
        } catch (IOException e) {
            log.error("处理来自客户端：{}的请求失败，原因是：{}",
                    socket.getInetAddress() + ":" + socket.getPort(), e.getMessage());
        }
    }
}
